import { Component, ViewChild, OnInit, EventEmitter, Input, Output, Host, SimpleChanges, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppComponent } from '../../../app.component';
import { environment } from '../../../../environments/environment';
import { UtilsService } from '../../../shared/services/utils.service';
import { ResearchGlobalCompactService } from './researchGlobalCompact.service';
import { Subscription } from 'rxjs/Subscription';
import { ColumnOptions } from '../../../shared/components/table/models/columnOptions.model';
import { PaginationPositionDisplayEnum, TableComponent } from '../../../shared/components/table/table.component';
import { GlobalCompactPrincipleModel } from './models/globalCompactPrinciple.model';
import { GlobalCompactFilterModel } from './models/globalCompactFilter.model';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { GlobalCompactListModel } from './models/globalCompactList.model';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';
import { AnalyticsService } from '../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../shared/models/googleAnalytics.model';
import { BaseComponent } from '../../../shared/components/baseComponent/base.component';


/**
 * Overall global compact main component
 *
 * Author: Sorin Spiru, Andrei Istrate
 * Date: 13.01.2018 , 09.05.2018
 */
export enum GlobalCompactListEnum {
    NonCompliantAndWatchlist = 0,
    NonCompliant = 1,
    Watchlist = 2
}

@Component({
    moduleId: module.id,
    templateUrl: 'researchGlobalCompact.component.html',
    styleUrls: ['../research.component.scss'],
    providers: [UtilsService, ResearchGlobalCompactService]
})
export class ResearchGlobalCompactComponent extends BaseComponent {
    constructor(@Host() private rootComponent: AppComponent,
        private globalCompactService: ResearchGlobalCompactService,
        private analyticsService: AnalyticsService,
        private cdRef: ChangeDetectorRef
    ) {
        super(cdRef);
    }

    public readonly resourcesUrl: string = environment.resourcesUrl;

    public sub: Subscription;
    public assessmentsList: any[];
    public columns: ColumnOptions[];
    public subIndustryList: any[];
    public source: any[];
    public elementCount: number;
    public filter: GlobalCompactFilterModel = new GlobalCompactFilterModel();//EsgFilterModel = new EsgFilterModel();
    public paginationPosition = PaginationPositionDisplayEnum.UpAndDown;
    public principlesSelected: GlobalCompactListEnum;
    public principlesOption = GlobalCompactListEnum;

    @ViewChild('table') table: TableComponent;

    ngOnInit() {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('Global Compact Landing Page', 'Landing Pages', {}));
        if(!this.productPermissions.globalcompact) this.rootComponent.finishLoading();
        this.loadTable(GlobalCompactListEnum.NonCompliantAndWatchlist);
    }

    public loadTable(principlesSelected: GlobalCompactListEnum) {
        this.principlesSelected = principlesSelected;
        this.resetTable()
        this.setColumns();
        this.getBulkCompanies(new TableOptions("companyProfile.name"));
    }

    private resetTable() {
        this.source = [];
        this.columns = [];
        this.filter = new GlobalCompactFilterModel();
    }

    private setColumns() {
        this.columns = [
            new ColumnOptions('companyProfile.nameLowercase', 'CompanyNameLowerCase', 'Company Name', 'col-md-4', true, false, false, undefined, false, true, false)
        ];

        switch(this.principlesSelected){
            case GlobalCompactListEnum.Watchlist:
                this.filter.OverallAssessmentFilter = "1";
                this.columns.push(new ColumnOptions('companyProfile.nameLowercase', 'PrinciplesWLStrFilter', 'Principle(s) at Risk of Breach', 'col-md-4', false, false, false, undefined/*GlobalCompactPrincipleModel.getPrinciples()*/, false, false, false,true, undefined, false, false, true));
                this.columns.push(new ColumnOptions('industry', 'industry', 'SubIndustry', 'col-md-4', false, false, false, undefined, false, false, false ,true, undefined, false, false, true));
                break;
            case GlobalCompactListEnum.NonCompliant:
                this.filter.OverallAssessmentFilter = "2";
                this.columns.push(new ColumnOptions('companyProfile.nameLowercase', 'PrinciplesNCStrFilter', 'Principle(s) Breached', 'col-md-4', false, false, false, undefined /*GlobalCompactPrincipleModel.getPrinciples()*/, false, false, false,true, undefined, false, false, true));
                this.columns.push(new ColumnOptions('SubPeerGroup', 'subPeerGroup', 'SubIndustry', 'col-md-4', false, false, false, undefined, false, false, false ,true, undefined, false, false, true));
                break;
            default:
                this.filter.OverallAssessmentFilter = "";
                this.columns.push(new ColumnOptions('companyProfile.nameLowercase', 'PrinciplesWLStrFilter', 'Principle(s) at<br />Risk of Breach', 'col-md-2', false, undefined, false, undefined/*GlobalCompactPrincipleModel.getPrinciples()*/, false, false, false,true, undefined, false, false, true));
                this.columns.push(new ColumnOptions('companyProfile.nameLowercase', 'PrinciplesNCStrFilter', 'Principle(s) Breached', 'col-md-2', false, false, false, undefined/*GlobalCompactPrincipleModel.getPrinciples()*/, false, false, false,true, undefined, false, false, true));
                this.columns.push(new ColumnOptions('SubPeerGroup', 'subPeerGroup', 'SubIndustry','col-md-4', false, false, false, undefined, false, false, false,true, undefined, false, false, true));
                break;
        }
    }

    private getBulkCompanies(tableOptions: TableOptions): void {
        this.globalCompactService.getCompaniesCount(this.filter).subscribe(data => {
            this.elementCount = data;
        });
        this.filter.PrinciplesNCStrFilter = UtilsService.arrayToStringWithPipes(this.filter.PrinciplesNCStrFilter);
        this.filter.PrinciplesWLStrFilter = UtilsService.arrayToStringWithPipes(this.filter.PrinciplesWLStrFilter);

        this.globalCompactService.getCompanies(this.filter, tableOptions.pageOptions.skip, tableOptions.pageOptions.take, tableOptions.orderByCol, tableOptions.orderByAsc).subscribe(data => {
            if (tableOptions.pageOptions.listOnly == false) {
                this.table.ResetPaginationToFirstPage();
            }
            let valuesToDisplay: any[];
            if (this.principlesSelected == GlobalCompactListEnum.Watchlist) {
                valuesToDisplay = data.map(company => {
                    return {
                        company: new TableRouterLink(company.companyProfile.name, true, company.companyProfile.nameUrlFriendly, 'globalcompact'),
                        assessmentWL: this.arrayOfPrinciplesToString(company.watchListPrinciples),
                        subPeerGroup: company.companyProfile.industry
                    };
                });
            }
            else if (this.principlesSelected == GlobalCompactListEnum.NonCompliant) {
                valuesToDisplay = data.map(company => {
                    return {
                        company: new TableRouterLink(company.companyProfile.name, true , company.companyProfile.nameUrlFriendly, 'globalcompact'),
                        assessmentNC: this.arrayOfPrinciplesToString(company.nonCompliantPrinciples),
                        subPeerGroup: company.companyProfile.industry
                    };
                });
            }
            else {
                valuesToDisplay = data.map(company => {
                    return {
                        company: new TableRouterLink(company.companyProfile.name, true , company.companyProfile.nameUrlFriendly, 'globalcompact'),
                        assessmentWL: this.arrayOfPrinciplesToString(company.watchListPrinciples),
                        assessmentNC: this.arrayOfPrinciplesToString(company.nonCompliantPrinciples),
                        subPeerGroup: company.companyProfile.industry
                    };
                });
            }
            this.source = valuesToDisplay;
        });

    }

    private arrayOfPrinciplesToString(principles: any[]): string {
        if (principles.length == 0) return "N/A";
        let result: string = "";
        principles.forEach(principle => {
            result += " " + principle.name;
        });
        return result;
    }

    public tableOptionsChanged(tableOptions: TableOptions): void {
        this.getBulkCompanies(tableOptions);
    }

    ngAfterViewInit() {
        this.rootComponent.finishLoading();
    }
}